package cn.bonoon.controllers.schedule;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.bonoon.core.plugins.HolidayService;
import cn.bonoon.core.plugins.PersonalHolidayService;
import cn.bonoon.core.plugins.ScheduleService;
import cn.bonoon.entities.plugins.HolidayEntity;
import cn.bonoon.entities.plugins.PersonalHolidayEntity;
import cn.bonoon.entities.plugins.ScheduleEntity;
import cn.bonoon.kernel.util.StringHelper;
import cn.bonoon.kernel.web.models.JsonResult;

/**
 * 日程安排-年视图
 * @author ocean~
 */
@Controller
@RequestMapping("s/user/schedule")
public class ScheduleYearViewController extends AbstractSchedule {
	
	@Autowired
	public ScheduleYearViewController(HolidayService holidayService, PersonalHolidayService personalHolidayService, ScheduleService scheduleService) {
		super(holidayService, personalHolidayService, scheduleService);
	}
	
	@RequestMapping(value = "view/year", method = { POST, GET })
	public String yearView(Model model, HttpServletRequest request, Integer year) {
		if (null == year) {
			year = Calendar.getInstance().get(Calendar.YEAR);
		}
		model.addAttribute("year", year);
		model.addAttribute("content", viewYear(year));
		return "user/schedule/schedule-view-year";
	}
	
	@ResponseBody
	@RequestMapping(value = "view/refresh_year", method = { RequestMethod.GET, RequestMethod.POST })
	public JsonResult refresh_yearView(Integer year, Model model) {
		if (null == year) {
			year = Calendar.getInstance().get(Calendar.YEAR);
		}
		return JsonResult.result(viewYear(year));
	}
	
	@ResponseBody
	@RequestMapping(value = "view/year_today", method = { RequestMethod.GET, RequestMethod.POST })
	public JsonResult view_year_today(Model model) {
		Calendar cal = Calendar.getInstance();
		return JsonResult.result(viewYear(cal.get(Calendar.YEAR)));
	}
	
	private String viewYear(int year) {
		StringBuilder content = new StringBuilder();
		// -------------------- thead --------------------
		content.append("<tr>");
		content.append("<td colspan='24' style='text-align:center;height:50px;'>");
		content.append("<span style='float:left;'>");
		content.append("<a href='#' class='bupabutton' data-settings='flat:true' id='a_today'>今天</a>&nbsp;&nbsp;");
		content.append("年份：<select style='width:100px;' id='sel_year'>");
		int current_year = Calendar.getInstance().get(Calendar.YEAR);
		for (int i = current_year; i < (current_year + 10); i++) {
			if (i == year) {
				content.append("<option value='" + i + "' selected='selected' >" + i + "</option>");
			} else {
				content.append("<option value='" + i + "'>" + i + "</option>");
			}
		}
		content.append("</select></span>");
		content.append("<strong><span style='font-size:16px;'><span id='title_year'>").append(year).append("</span>年行程安排</span></strong>");
		content.append("<span style='float:right;'>");
		content.append("<img src='/res/images/holiday.png'/>：公共节假日&nbsp;&nbsp;");
		content.append("<img src='/res/images/windmill.png'/>：个人假日&nbsp;&nbsp;");
		content.append("<img src='/res/images/detail.png'/>：行程日志&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
		content.append("<a href=\"#\" class=\"bupabutton\" data-settings='flat:true' id=\"a_weekview\">&nbsp;周&nbsp;</a>");
		content.append("<a href=\"#\" class=\"bupabutton\" data-settings='flat:true' id=\"a_monthview\">&nbsp;月&nbsp;</a>");
		content.append("<a href=\"#\" class=\"bupabutton\" data-settings='flat:true' id=\"a_yearview\" data-settings=\"selected:true\">&nbsp;年&nbsp;</a>");
		content.append("</span></td></tr>");
		content.append("<tr>");
		content.append("<th style='width:70px;text-align:center;'>月份/星期</th>");
		content.append("<th style='background-color:#0C3;width:30px;text-align:center;'>日</th>");
		content.append("<th style='width:30px;text-align:center;'>一</th>");
		content.append("<th style='width:30px;text-align:center;'>二</th>");
		content.append("<th style='width:30px;text-align:center;'>三</th>");
		content.append("<th style='width:30px;text-align:center;'>四</th>");
		content.append("<th style='width:30px;text-align:center;'>五</th>");
		content.append("<th style='width:30px;text-align:center;'>六</th>");
		content.append("<td style='width:2px;background:#ededed;'></td>");
		content.append("<th style='background-color:#0C3;width:30px;text-align:center;'>日</th>");
		content.append("<th style='width:30px;text-align:center;'>一</th>");
		content.append("<th style='width:30px;text-align:center;'>二</th>");
		content.append("<th style='width:30px;text-align:center;'>三</th>");
		content.append("<th style='width:30px;text-align:center;'>四</th>");
		content.append("<th style='width:30px;text-align:center;'>五</th>");
		content.append("<th style='width:30px;text-align:center;'>六</th>");
		content.append("<td style='width:2px;background:#ededed;'></td>");
		content.append("<th style='background-color:#0C3;width:30px;text-align:center;'>日</th>");
		content.append("<th style='width:30px;text-align:center;'>一</th>");
		content.append("<th style='width:30px;text-align:center;'>二</th>");
		content.append("<th style='width:30px;text-align:center;'>三</th>");
		content.append("<th style='width:30px;text-align:center;'>四</th>");
		content.append("<th style='width:30px;text-align:center;'>五</th>");
		content.append("<th style='width:30px;text-align:center;'>六</th>");
		content.append("</tr>");
		// -------------------- tbody --------------------
		HolidayEntity holiday = holidayService.getYear(year);
		String[] months = new String[12];
		if (null != holiday) {
			months[0] = holiday.getJanuary();
			months[1] = holiday.getFebruary();
			months[2] = holiday.getMarch();
			months[3] = holiday.getApril();
			months[4] = holiday.getMay();
			months[5] = holiday.getJune();
			months[6] = holiday.getJuly();
			months[7] = holiday.getAugust();
			months[8] = holiday.getSeptember();
			months[9] = holiday.getOctober();
			months[10] = holiday.getNovember();
			months[11] = holiday.getDecember();
		}
		
		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, year);
		List<PersonalHolidayEntity> personalHolidays = personalHolidayService.getYear(getUser(), year);
		List<ScheduleEntity> schedules = scheduleService.getYear(getUser(), year);
		
		for (int i = 0; i < months.length; i++) {
			c.set(Calendar.MONTH, i);
			int day_count = c.getActualMaximum(Calendar.DAY_OF_MONTH); // 当前月的天数
			int week_of_minday = week_of_minday(year, i + 1); // 当前月第一天是星期几
			content.append("<tr><th style='text-align:center;' rowspan='2'>");
			content.append(format_month(i));
			content.append("</th>");
			for (int k = 1; k < week_of_minday; k++) {
				content.append("<td></td>");
			}
			int week = week_of_minday;
			int br = 0;
			String m = months[i];
			int[] holidays = null;
			int holidays_len = 0;
			if (StringHelper.isNotEmpty(m)) {
				holidays = StringHelper.tointArray(m);
				holidays_len = holidays.length;
			}

			for (int j = 1, index = 0; j <= day_count; j++) {
				if (null != holidays) {
					if (index < holidays_len && holidays[index] == j) {
						content.append("<td style='text-align:center;cursor:default;position:relative;' class='day selectedDay'>");
						index++;
					} else {
						content.append("<td style='text-align:center;cursor:default;position:relative;' class='day'>");
					}
				} else {
					if (week == 1 || week == 7) {
						content.append("<td style='text-align:center;cursor:default;position:relative;' class='day selectedDay'>");
					} else {
						content.append("<td style='text-align:center;cursor:default;position:relative;' class='day'>");
					}
				}
				content.append("<input type='hidden' class='month").append(i).append("' value='").append(j).append("' />");
				// 当天是否开始个人假日（持续N天）
				if (null != personalHolidays) {
					for (PersonalHolidayEntity ph : personalHolidays) {
						if (ph.getYear() == year && ph.getMonth() == i && ph.getDate() == j) {
							content.append("<img src='/res/images/windmill.png' name='img_personalHoliday' style='position:absolute;left:0;top:0;' />");
							break;
						}
					}
				}
				// 当天是否存在行程安排
				if (null != schedules) {
					for (ScheduleEntity s : schedules) {
						Calendar executeAt = Calendar.getInstance();
						executeAt.setTime(s.getExecuteAt());
						if (executeAt.get(Calendar.YEAR) == year && executeAt.get(Calendar.MONTH) == i && executeAt.get(Calendar.DATE) == j) {
							content.append("<img src='/res/images/detail.png' name='img_schedule' style='position:absolute;left:0;bottom:0;'/>");
							break;
						}
					}
				}
				content.append(j).append("</td>");
				if (week == 7) {
					if (++br == 3) {
						br = 0;
						content.append("</tr><tr>");
					} else {
						content.append("<td style='background:#ededed;'></td>");
					}
				}
				if (++week > 7) {
					week = 1;
				}
			}
			week = --week < 1 ? 7 : week; // 当月最后一天的星期
			int colspan = 23 - (week == 7 ? br * 8 : br * 8 + week);
			content.append("<td colspan='" + colspan + "'></td>");
			content.append("</tr>");
		}
		content.append("<input id='year' type='hidden' value='").append(year).append("'/>");
		content.append("<input id='month' type='hidden' />");
		content.append("<input id='date' type='hidden' />");
		return content.toString();
	}
}
